//抛物线飞入购物车
(function($){
    //属性项
    var $goodsItemProp = $("#goodsItemProp");
    var propertyItems = $goodsItemProp.find(".books-property");
    var $cartSize = $("#cartSize");//购物车商品数量
    var $numberIpt = $(".js-number-input");

    //默认选中第一个
    propertyItems.first().addClass("on");
    PropertySelect(propertyItems.first());

    //如果购物车有商品，则显示内容
    if(parseInt($cartSize.text()) != 0){
        $cartSize.show();
    }

    //判断属性项
    $(".propItem").on("click", function(){
        console.log(111);
        var $goodsItems = $(this);
        PropertySelect($goodsItems);
    });

    //数量选择器
    $(document).on("click", ".js-numberbox", function(e){
        var $target = $(e.target);

        if($target.hasClass("js-number-sub")){
            NumberSub($target);
        }
        else if($target.hasClass("js-number-plus")){
            NumberPlus($target);
        }
    });

    $numberIpt.on("input propertychange", function(){
        var $this = $(this);

        OptionIpt($this);
    });

    $numberIpt.on("keyup", function(){
        var val = parseInt(this.value);

        if (isNaN(val) || val <= 0) {
            val = 1;
        }
        if (this.value != val) {
            this.value = val;
        }
    });

    //选择商品材质
    function PropertySelect(item){

        var data = item.attr("goodsitem-full");

        var goodsItemId = data.split("@")[0];
        var goodsItemName = data.split("@")[1];
        var goodsItemOrignPrice = data.split("@")[2];
        var goodsItemDiscntPrice = data.split("@")[3];
        var goodsItemImage = data.split("@")[4];

        $("#goodsItemId").val(goodsItemId);
        $("#goodsItemName").html(goodsItemName);
        $("#goodsItemOrignPrice").text(goodsItemOrignPrice);
        $("#goodsItemDiscntPrice").text(goodsItemDiscntPrice);
        $("#midimg").attr("src",goodsItemImage);

        item.addClass("on").siblings().removeClass("on");

    }

    function isEqual(){
        var equal = false;

        //如果商品条目id相同则增加购物车当前商品数，不同则添加新的商品条目
        $(".js-cart-list").find(".js-cart-item").each(function(){
            var itemId = $(this).attr("data-itemId");
            var currentId = $("#goodsItemId").val();//当前商品条目id

            if(currentId == itemId){
                var $count = $(this).find(".js-item-count");
                var count = parseInt($count.text());

                equal = true;
                count += parseInt($(".js-number-input").val());
                $count.text(count);
                getSubtotal($(this));//计算价格
            }
        });

        return equal;
    }

    //拼接当前商品条目到购物车
    function jointHtml(){
        var img = $("#midimg").attr("src");
        var name = $("#goodsItemName").text();
        var discntPrice = $("#goodsItemDiscntPrice").text();
        var number = $("#number").val();
        var itemId = $("#goodsItemId").val();
        var goodsId = $("#addCart").attr("data-goodsid");
        var size = parseInt($cartSize.text());
        var html = '';

        html = '<a class="cart-item js-cart-item" data-itemId="' + itemId + '" href="items?id='+ goodsId + '">'
            + '<div class="media">'
            + '<div class="media-left cart-item__img">'
            + '<img src="'+ img +'" width="84" height="64" alt="书">'
            + '</div>'
            + '<div class="media-body cart-item__body">'
            + '<h4 class="media-heading cart-item__name">'+ name +'</h4>'
            + '<div class="cart-item__price">'
            + '<em>¥<span class="js-unit-price">' + discntPrice + '</span></em>'
            + ' <span class="cart-item__count">x<span class="js-item-count">' + number + '</span></span>'
            + '</div>'
            + '</div>'
            + '</div>'
            + '</a>';

        size++;
        $cartSize.text(size).show();
        $("#totalSize").text(size);
        $(".js-cart-content").find(".js-cart-list").append(html);
        $(".js-cart-item").each(function(){
            getSubtotal($(this));
        });
        $(".js-cart-wrapper").hover(function(){
            $(this).find(".js-cart-content").show();
        }, function(){
            $(this).find(".js-cart-content").hide();
        });
    }

    //数量减
    function NumberSub(element) {
        var $parent = element.closest(".js-numberbox");
        var $ipt = $parent.find(".js-number-input");
        var iptValue = parseInt($ipt.val());

        if(!isNaN(iptValue)){
            iptValue--;
            if(iptValue <= 1){
                iptValue = 1;
                element.addClass("mallui_number-disabled");
            }
            $ipt.val(iptValue);
        }
    }

    //数量加
    function NumberPlus(element) {
        var $parent = element.closest(".js-numberbox");
        var $ipt = $parent.find(".js-number-input");
        var $subElement = $parent.find(".js-number-sub");
        var iptValue = parseInt($ipt.val());

        if(!isNaN(iptValue)){
            iptValue++;
            $ipt.val(iptValue);
            $subElement.removeClass("mallui_number-disabled");
        }
    }

    //操作数量输入框
    function OptionIpt(input){
        var $subElement = input.prev(".js-number-sub");
        var $parent = input.closest(".js-numberbox");
        var iptValue = parseInt(input.val());

        if(!isNaN(iptValue)){
            if(iptValue < 1) {
                input.val(1);
                $subElement.addClass("mallui_number-disabled");
            }
            else if(iptValue == 1){
                $subElement.addClass("mallui_number-disabled");
            }
            else{
                $subElement.removeClass("mallui_number-disabled");
            }
        }
    }

    //计算单行价格
    function getSubtotal(parent){
        var unitPrice = parseFloat(parent.find(".js-unit-price").text());
        var num = parseInt(parent.find(".js-item-count").text());
        var subtotal = 0;

        subtotal = parseInt(num) * parseFloat(unitPrice).toFixed(2);

        parent.data("subtotal", subtotal);
        getTotal();
    }

    //更新合计
    function getTotal(){
        var $settleAccounts = $("#settleAccounts");
        var $totalPrice = $("#totalPrice");
        var total = 0;

        $(".js-cart-list").find(".js-cart-item").each(function(){
            var $this = $(this);
            var unitPrice = parseFloat($this.find(".js-unit-price").text());
            var num = parseInt($this.find(".js-item-count").text());
            var singlePrice = parseInt(num) * parseFloat(unitPrice).toFixed(2);
            var subtotal = $this.data("subtotal") || singlePrice;

            total += subtotal;
        });

        $totalPrice.text(total.toFixed(2));
    }

    $("#payBtn").on("click", function(e){   //是$("#payBtn")这个元素点击促发的 开始动画的位置就是这个元素的位置为起点
        var count = $("#number").val();
        var goodsItemId = $("#goodsItemId").val();

        location.href = $("#contextPath").val()+"/orderPc/orderConfirm?goodsItemIds=" + goodsItemId + "&counts=" + count;

    });

    $("#addCart").on("click", function(e){   //是$("#addcar")这个元素点击促发的 开始动画的位置就是这个元素的位置为起点
        var $addcar = $(this);

        var offset = $("#end").offset();  //结束的地方的元素
        var img = $addcar.closest(".books-content").find('.mid-img').attr('src');
        var flyer = $('<img class="u-flyer" src="'+img+'">');

        var data = $addcar.attr("data-full");
        var goodsId = data.split("@")[0];
        var sellerId = data.split("@")[1];
        var goodsItemId = $("#goodsItemId").val();
        var count = $("#number").val();

        $.ajax({
            url: "intoCart",
            type: "post",
            dataType: 'json',
            data : {
                goodsId:goodsId,
                sellerId:sellerId,
                goodsItemId:goodsItemId,
                count:count
            },
            success: function(data) {
                if (data.returnFlag == '0') {
                    //------------加入购物车成功
                    flyer.fly({
                        start: {
                            left: e.clientX,
                            top: e.clientY
                        },
                        end: {
                            left: offset.left,
                            top: offset.top-$(document).scrollTop(),
                            width: 0,
                            height: 0
                        },
                        onEnd: function(){
                            var $list = $(".js-cart-list");
                            var $item = $list.find(".js-cart-item");

                            //如果购物车商品数为空，则添加当前商品条目
                            if($item.length == 0){
                                jointHtml();
                            }
                            else{
                                if(!isEqual()){
                                    jointHtml();
                                }
                            }

                            $("#msg").show().animate({width: '250px'}, 500).fadeOut(2000);
                            this.destory();
                        }
                    });
                }
                else if (data.returnFlag == '1'){
                    location.href = $("#contextPath").val()+"/user/loginPage";
                }
                else if (data.returnFlag == '2'){
                    layer.open({
                        content: data.rtnMsg,
                        scrollbar: false
                    });
                }
            },
            error: function(xhr, type, errorThrown) {
                //异常处理；
                alert("请稍后再试!");
            }
        });
    });
})(jQuery);